﻿Imports System.Web
Imports System.Web.Services
Imports System.Web.SessionState
Imports MeoTom.Core.BLL
Imports System.IO
Imports MeoTom.Core

Public Class ValidateComment
    Implements IReadOnlySessionState, System.Web.IHttpHandler
    Private strMsg As String = ""

    Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        Dim util As New Utilities.Common()
        Dim objComment As New Comments()
        Dim strOut As String = ""
        Dim iArticleID As Integer = 0
        Dim strPageID As String = ""
        context.Response.ContentType = "text/plain"
        Try
            If context.Request.Form("txtTypeComment").ToString = "1" Then
                objComment.PageID = context.Request("txtId")
                objComment.ArticleId = 0
                strPageID = objComment.PageID
            ElseIf context.Request.Form("txtTypeComment").ToString = "0" Then
                objComment.ArticleId = util.IntValue(context.Request("txtId").Replace(".aspx", "").Replace(".htm", "")).ToString()
                objComment.PageID = "0"
                iArticleID = objComment.ArticleId
            End If

            If objComment.ArticleId = 0 And objComment.PageID.Length = 0 Then
                context.Response.Write("Error !! Plz try again letter...")
            Else
                Dim txtTitleTemp As String = context.Server.HtmlDecode(context.Server.UrlDecode(context.Request.Form("txtTitle")))
                Dim txtUrlTemp As String = context.Request.Form("txtArticleURL")

                objComment.AddedBy = util.NoHTML(context.Request("txtFullName"))
                objComment.AddedByEmail = util.NoHTML(context.Request("txtEmail"))
                objComment.AddedByIP = context.Request.UserHostAddress
                objComment.AddedByURL = util.NoHTML(context.Request("txtYourUrl"))
                objComment.Body = context.Request("txtBody")

                If util.GetCookie("UserName") <> vbNullString Then
                    objComment.IsAdmin = True
                ElseIf util.GetSession("UserName") <> vbNullString Then
                    objComment.IsAdmin = True
                Else
                    objComment.IsAdmin = False
                End If

                If ValidateRequest(context, objComment, util.GetSession("CaptchaImageText"), context.Request("txtCode")) Then
                    If objComment.AddedByURL.Length <= 7 Then
                        objComment.AddedByURL = ""
                    End If

                    If objComment.AddedBy.Length < 1 Or objComment.AddedBy = "Họ và tên" Then
                        objComment.AddedBy = "Guest"
                    End If

                    objComment.Body = util.FormatMultiline(util.BBCode(util.ConvertEmoticon("http://blog.meotom.net", context.Request("txtBody"))))
                    objComment.Create()

                    Dim MatchResult As Match = Regex.Match(objComment.Body, "@(?<Users>.*?):")
                    While MatchResult.Success
                        Using dc As New MeoTomDataContext
                            Dim EmailUserSrc = dc.Justin_Comments_GetByEmail(MatchResult.Groups("Users").Value, strPageID, iArticleID)

                            For Each EmailItem In EmailUserSrc
                                'EmailItem.AddedByEmail
                                Using Mailer As New MeoTom.Web.Blog.Services.Util.MeoTom_Services
                                    Using reader As New System.IO.StreamReader(Configs.FolderSaveData & "ReplyComment.htm", System.Text.Encoding.UTF8)
                                        Dim strBodyMail As String = reader.ReadToEnd()
                                        strBodyMail = strBodyMail.Replace("{0}", txtTitleTemp)
                                        strBodyMail = strBodyMail.Replace("{1}", objComment.AddedBy)
                                        strBodyMail = strBodyMail.Replace("{2}", objComment.Body)
                                        strBodyMail = strBodyMail.Replace("{3}", txtUrlTemp)
                                        strBodyMail = strBodyMail.Replace("{4}", EmailItem.AddedBy)
                                        strBodyMail = strBodyMail.Replace("{5}", Configs.WebName)

                                        Mailer.SendMail(EmailItem.AddedByEmail, "MeoTom.Net: New Comment Alert!", strBodyMail, "")
                                    End Using
                                End Using
                                Exit For
                            Next
                        End Using
                        MatchResult = MatchResult.NextMatch
                    End While

                    If Configs.IsCommentAlert Then
                        Using Mailer As New MeoTom.Web.Blog.Services.Util.MeoTom_Services
                            Using reader As New System.IO.StreamReader(Configs.FolderSaveData & "CommentAlert.htm", System.Text.Encoding.UTF8)
                                Dim strBodyMail As String = reader.ReadToEnd()
                                strBodyMail = strBodyMail.Replace("{0}", txtTitleTemp)
                                strBodyMail = strBodyMail.Replace("{1}", objComment.AddedBy)
                                strBodyMail = strBodyMail.Replace("{2}", objComment.Body)
                                strBodyMail = strBodyMail.Replace("{3}", txtUrlTemp)

                                Mailer.SendMail(Configs.WebReportEmail1, "MeoTom.Net: New Comment Alert!", strBodyMail, "")
                            End Using
                        End Using
                    End If

                    context.Response.Write("Cam on ban da Comment!_," & objComment.AddedBy.Replace(",", "") & "," & String.Format("{0:HH:mm tt}", DateTime.Now) & "," & objComment.Body.Replace(",", "") & "," & String.Format("{0:dd/MM/yyyy}", DateTime.Now))
                Else
                    context.Response.Write(strMsg)
                End If
            End If
        Catch ex As Exception
            context.Response.Write(ex.Message)
        Finally
            util = Nothing
            objComment = Nothing
        End Try
    End Sub

    Function ValidateRequest(ByVal context As HttpContext, ByVal objComment As Comments, ByVal CodeSecure As String, ByVal YourCode As String) As Boolean
        Try
            If YourCode.Equals(CodeSecure) Then
                Dim reg As New Regex("^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$")
                Dim regUrl As New Regex("(((http|ftp|https|ftps)://))+(([a-zA-Z0-9\._-]+\.[a-zA-Z]{2,6})|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(/[a-zA-Z0-9\&amp;%_\./-~-]*)?")
                If objComment.AddedByEmail.Length < 1 Then
                    strMsg = "* Xin vui lòng nhập Email."
                    Return False
                ElseIf objComment.AddedByEmail.Length > 50 Then
                    strMsg = "* Email quá dài."
                    Return False
                ElseIf Not reg.IsMatch(objComment.AddedByEmail) Then
                    strMsg = "* Email sai định dạng."
                    Return False
                ElseIf objComment.Body.Length < 1 Then
                    strMsg = "* Xin vui lòng nhập nội dung comment."
                    Return False
                Else
                    If objComment.AddedByURL.Length > 7 Then
                        If Not regUrl.IsMatch(objComment.AddedByURL) Then
                            strMsg = "* Website sai định dạng. (http://)"
                            Return False
                        Else
                            If CheckIP(objComment) Then
                                strMsg = "* Your IP Blocked. Plz contact administrator."
                                Return False
                            Else
                                Return True
                            End If
                        End If
                    Else
                        If CheckIP(objComment) Then
                            strMsg = "* Your IP Blocked. Plz contact administrator."
                            Return False
                        Else
                            Return True
                        End If
                    End If
                End If
            Else
                strMsg = "* Sai mã xác nhận."
                Return False
            End If
        Catch ex As Exception
            strMsg = ex.Message
            Return False
        End Try
    End Function

    Public Function CheckIP(ByVal objComment As Comments) As Boolean
        Dim IPToBlock As String = objComment.AddedByIP & "|"
        Dim strOld As String = ""
        Dim reader As New StreamReader(Configs.FolderSaveData & "IPBlock.jt", System.Text.Encoding.UTF8)
        strOld = reader.ReadToEnd()
        reader.Close()

        If strOld.Contains(IPToBlock) Then
            Return True
        Else
            Return False
        End If
    End Function

    ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property

End Class